<?php

namespace IMT\ServicesBundle\Controller;

use BeSimple\SoapBundle\ServiceDefinition\Annotation as Soap;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use IMT\ServicesBundle\Models\Event\EventOperationResponse;
use IMT\ServicesBundle\Models\Event\EventGetRequest;

class EventController extends Controller
{
	/**
     * @Soap\Method("get")
     * @Soap\Param("request", phpType = "\IMT\ServicesBundle\Models\Event\EventGetRequest")
     * @Soap\Result(phpType = "\IMT\ServicesBundle\Models\Event\EventOperationResponse")
     */
    public function getAction($request)
    {
    	try {
	    	if(intval($request->getId()) == 0)
	    		throw new \SoapFault('ID_NOT_VALID', 'L\'id est incorrect : '.$request->getId());

	    	// Authentification du user
	    	$userManager = $this->get('fos_user.user_manager');
	    	$user = $userManager->findUserBy(array('username' => $request->getUserAccount()->getUsername()));
	    	
	    	$encoder_service = $this->get('security.encoder_factory');
	    	$encoder = $encoder_service->getEncoder($user);
	    	$encoded_pass = $encoder->encodePassword($request->getUserAccount()->getPassword(), $user->getSalt());
	    	
	    	if (!$user)
	    		throw new \SoapFault('USER_NOT_FOUND', 'L\'identifiant ou le mot de passe du compte utilisateur est incorrect');
	    	else if($user->getPassword() != $encoded_pass)
	    		throw new \SoapFault('USER_NOT_FOUND', 'L\'identifiant ou le mot de passe du compte utilisateur est incorrect');
	    		    	
	    	// Récupération de l'event
	    	$repository = $this->getDoctrine()->getRepository('IMTEventBundle:Event');
    		$event = $repository->findOneById($request->getId());
    		
    		if (!$event)
    			throw new \SoapFault('EVENT_NOT_FOUND', 'L\'event ayant l\'id '.$request->getId().' n\'existe pas');
    		
    		//$event->setDatesToString();
    		
    		return $this->container->get('besimple.soap.response')->setReturnValue(new EventOperationResponse($event));
    	} catch(\SoapFault $e) {
    		return $this->container->get('besimple.soap.response')->setReturnValue(new EventOperationResponse($e));
    	} catch(\Exception $e) {
    		$logger = $this->get('logger');
    		$logger->err('[SOAP] EventService : Erreur lors de l\'envoi des données. Code :'.$e->getCode().' Message :'.$e->getMessage());
    		
    		return $this->container->get('besimple.soap.response')->setReturnValue(
    			new EventOperationResponse(
    				new \Exception('Une erreur interne est survenue', -1)
    			)
    		);
    	}
    }
    
    private function convertDate($object)
    {
    	ob_start();
    	var_dump(get_object_vars($object));
    	$content = ob_get_contents();
    	ob_end_clean();
    	
    	return $content;
    }
}
